package ua.org.enginer.tracking
{
	import com.google.analytics.AnalyticsTracker;
	
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	
	import mx.core.EventPriority;
	import mx.core.UIComponent;
	
	public class UIComponentTrackingImpl implements ITrackingObject
	{
		public var target:Object
		private var _tracker:AnalyticsTracker
		
		public function set tracker(value:AnalyticsTracker):void {
			_tracker = value
		}
		
		public function get tracker():AnalyticsTracker {
			return _tracker
		}
		
		public function UIComponentTrackingImpl(target:UIComponent)
		{
			this.target = target
			
			target.addEventListener(MouseEvent.CLICK, mouseClickHandler, false, EventPriority.DEFAULT+1, true);
			target.addEventListener(MouseEvent.DOUBLE_CLICK, mouseClickHandler, false, EventPriority.DEFAULT+1, true);
	  		target.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, EventPriority.DEFAULT+1, true);
		}
		
		protected function mouseClickHandler(event:MouseEvent):void
	    {
	    	if (trackingName && tracker) tracker.trackEvent(trackingName, "MouseEvent."+event.type)
	    }
		
		protected function keyDownHandler(event:KeyboardEvent):void
	    {
	    	if (trackingName && tracker) tracker.trackEvent(trackingName, "KeyboardEvent."+event.type)
	    }
	    
	    public function get trackingName():String
	    {
	    	if (target.hasOwnProperty('label')) 
	    		return target['label']
	    		
			return target.automationName || target.toolTip || target.name || target.id
	    }
	}
}